class PostsController < ApplicationController  
  before_filter :login_required, :except => [:index, :show]
  protect_from_forgery :only => [:create, :delete, :update] 

  def index
    #@posts = Post.find :all, :limit => 5, :order => "created_at desc"
    @posts = Post.paginate :page => params[:page], :order => "created_at desc"
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
      format.atom {
        @posts = Post.find :all, :limit => 15, :order => "created_at desc"
        render :layout => false
      }
    end
  end

  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @post }
    end
  end

  def new
    @post = Post.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @post }
    end
  end

  def edit
    @post = Post.find(params[:id])
  end

  def create
    @post = Post.new(params[:post])
    
    respond_to do |format|
      if @post.save
        current_user.posts << @post
        flash[:notice] = 'Post was successfully created.'
        format.html { redirect_to(:controller => :posts, :action => :products, :id => @post.id) }
        format.xml  { render :xml => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = 'Post was successfully updated.'
        format.html { redirect_to(@post) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to(admin_posts_url) }
      format.xml  { head :ok }
    end
  end
  
  def next_post
    @post = Post.find(params[:post_id])
    render :update do |page|
      page.replace_html :post, :partial => 'post'
    end
  end
  
  def products
    @post = Post.find(params[:id])
    @products = Product.find :all
  end
  
  def add_product
    post = Post.find(params[:post_id])
    product = Product.find(params[:product_id])
    post.products << product
    render :inline => "Done."
  end
  
  def remove_product
    post = Post.find(params[:post_id])
    product = Product.find(params[:product_id])
    post.products.delete(product)
    render :inline => "Done."
  end
end
